package com.panopset;

/**
 * Next field parser. Takes a String that contains a delimited String and parses
 * that String out, while preserving remaining text for further parsing.
 * 
 * @author Karl Dinwiddie
 * 
 */
public class NextFieldParser {

	/**
	 * Raw data input.
	 */
	private final String s;

	/**
	 * Remainder String.
	 */
	private String remainder;

	/**
	 * @param data
	 *            Raw data to parse.
	 */
	public NextFieldParser(final String data) {
		s = data;
	}

	/**
	 * 
	 * @param delim
	 *            Delimiter surrounding first field.
	 * @return Field value. If the data is <b>&quot;foo,bar,bat,&quot;L</b>,
	 *         then the returned value is <b>&quot;bar&quot;</b>, and the
	 *         remainder is <b>&quot;bat,&quot;</b>
	 * 
	 */
	public String parseFirstField(final String delim) {
		int i = s.indexOf(delim);
		if (i > -1 && s.length() > i + delim.length()) {
			String r = s.substring(i + delim.length());
			i = r.indexOf(delim);
			if (i > -1) {
				remainder = r.substring(i + 1);
				return r.substring(0, i);
			}
		}
		return "";
	}

	public String getRemainder() {
		if (remainder == null) {
			remainder = "";
		}
		return remainder;
	}
}
